package com.pool.store;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author claveld@gmail.com (David Clavel)
 */
public class Database {

  private static Database instance = null;
  
  private final Context context;
  private final String databaseName;
  private SQLiteDatabase database = null;
  
  public static void init(Context context, String databaseName) {
    if (instance == null) {
      instance = new Database(context, databaseName);
      instance.openOrCreateDatabase();
    }
  }
  
  public static Database get() {
    if (instance == null) {
      throw new UnsupportedOperationException("Call Database.init() before");
    }
    return instance;
  }

  public Database(Context context, String databaseName) {
    this.context = context;
    this.databaseName = databaseName;
  }
  
  public void openOrCreateDatabase() {
    database = context.openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);

//    database.execSQL("DROP TABLE IF EXISTS " + RecordStore.TABLE);
//    database.execSQL("DROP TABLE IF EXISTS " + RecordStore.TEMPORARY_TABLE);
//    database.execSQL("DROP TABLE IF EXISTS " + ShootStore.TABLE);

    database.execSQL("CREATE TABLE IF NOT EXISTS " + RecordStore.TABLE
        + " (Id VARCHAR, Timestamp VARCHAR, Player VARCHAR, ShootName VARCHAR, RemainingBalls INTEGER);");
    database.execSQL("CREATE TABLE IF NOT EXISTS " + RecordStore.TEMPORARY_TABLE
        + " (Id VARCHAR, Timestamp VARCHAR, Player VARCHAR, ShootName VARCHAR, RemainingBalls INTEGER);");

    database.execSQL("CREATE TABLE IF NOT EXISTS " + ShootStore.TABLE
        + " (Id VARCHAR, Description VARCHAR, Bonus INTEGER);");
  }
  
  public void close() {
    database.close();
    database = null;
    instance = null;
  }
  
  public Cursor query(
      String table,
      String[] columns,
      String selection,
      String[] selectionArgs,
      String groupBy,
      String having,
      String orderBy) {
    return database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
  }
  
  public void insert(String table, String nullColumnHack, ContentValues values) {
    database.insert(table, nullColumnHack, values);
  }
  
  public void update(String table, ContentValues values, String whereClause, String[] whereArgs) {
    database.update(table, values, whereClause, whereArgs);
  }
  
  public void delete(String table, String whereClause, String[] whereArgs) {
    database.delete(table, whereClause, whereArgs);
  }
}
